#include "utilityPredefine.h"
#include "CameraMoveCtrl.h"
#include "Camera.h"

CameraMoveCtrl::CameraMoveCtrl(void)
{
	bMove = false;
	bRotate = false;
	lastX = 0,lastY = 0;
	lastRX = 0,lastRY = 0;
}

CameraMoveCtrl::~CameraMoveCtrl(void)
{
}

bool CameraMoveCtrl::mouse(int button, int state, int x, int y)
{
	switch(button){
		case GLUT_LEFT_BUTTON:
			if(state == GLUT_DOWN){
				bMove = true;
				lastX = x;
				lastY = y;
			}
			if(state==GLUT_UP){
				bMove = false;
			}
			break;
		case GLUT_MIDDLE_BUTTON:
			if(state == GLUT_DOWN)
				;
			break;
		case GLUT_RIGHT_BUTTON:
			if(state == GLUT_DOWN){
				bRotate = true;
				lastRX = x;
				lastRY = y;
			}
			if(state == GLUT_UP){
				bRotate = false;
			}
		default:
			break;
	}
	return true;
}

bool CameraMoveCtrl::keyboard(unsigned char key, int x, int y)
{
	switch(key){
	case 'w':
	case 'W':
		camera->moveZ(-1);
		return true;
		break;
	case 's':
	case 'S':
		camera->moveZ(1);	
		return true;
		break;
	case 'a':
	case 'A':
		camera->moveX(-1);
		return true;
		break;
	case 'd':
	case 'D':
		camera->moveX(1);
		return true;
		break;
	}
	return false;
}

bool CameraMoveCtrl::motion(int x,int y)
{
	if(bMove){
		GLfloat mx = x - lastX,my = y-lastY;
		camera->moveX(0.05*mx);
		camera->moveY(-0.05*my);
	}
	lastX = x;
	lastY = y;

	if(bRotate){
		GLfloat rx = x - lastRX, ry = y - lastRY;
		Real pitch = camera->getPitch();
		Real yaw = camera->getYaw();
		pitch += -ry;
		if(pitch>85)			pitch = 85;
		if(pitch<-85)			pitch=-85;
		yaw += -rx;
		if(yaw>360)			yaw -= 360;
		if(yaw<-360)			yaw+=360;
		camera->setRotation(pitch,yaw,0);
	}
	lastRX = x;
	lastRY = y;
	return true;
}

void CameraMoveCtrl::setCamera(Camera* camera)
{
	this->camera = camera;
}